package com.mv.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mv.mapper.CardMapper;
import com.mv.mapper.CareMapper;
import com.mv.mapper.UserMapper;
import com.mv.mapper.WaresMapper;
import com.mv.pojo.Card;
import com.mv.pojo.Care;
import com.mv.pojo.Wares;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class CareServiceImpl implements CareService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CardMapper cardMapper;
    @Autowired
    private WaresMapper waresMapper;
    @Autowired
    private CareMapper careMapper;
    @Override
    public List<Care> getCareListByIntegral() {
        QueryWrapper<Care> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", 1);
        List<Care> careList = careMapper.selectList(queryWrapper);
        for (Care care : careList) {
            String userName = userMapper.selectById(care.getUserId()).getUserName();
            care.setUserName(userName);
        }
        return careList;
    }

    @Override
    public List<Care> getCareListByWares() {
        QueryWrapper<Care> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type",0);
        List<Care> careList = careMapper.selectList(queryWrapper);
        for (Care care : careList) {
            String userName = userMapper.selectById(care.getUserId()).getUserName();
            String waresName = waresMapper.selectById(care.getWaresId()).getWaresName();
            care.setUserName(userName).setWaresName(waresName);
        }
        return careList;
    }
    @Transactional
    @Override
    public void saveCareIntegral(Card card) {
        card.setIntegral(card.getIntegral()+card.getCareIntegral());
        cardMapper.updateById(card);
        Care care = new Care();
        care.setUserId(card.getUserId())
                .setType(1)
                .setIntegral(card.getCareIntegral())
                .setCardId(card.getId())
                .setCareTime(new Date());
        careMapper.insert(care);
    }
    @Transactional
    @Override
    public void saveCareWares(Wares wares) {
        wares.setCount(wares.getCount()-1);
        waresMapper.updateById(wares);
        Care care = new Care();
        care.setUserId(wares.getUserId())
                .setType(0)
                .setWaresId(wares.getId())
                .setCareTime(new Date());
        careMapper.insert(care);
    }
}

